package io.renren.modules.wxPay.controller;

import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayUtil;
import io.renren.config.WxPayConfig;
import io.renren.modules.wxPay.entity.WxpayEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("/wxPay")
public class WxPayController {
    @GetMapping("/pay")
    public Map<String, String> wxPayFunction() throws Exception {
        WxpayEntity wxpayEntity = new WxpayEntity();
        String notifyUrl = "";  //需要换成处理业务的回调接口

        WxPayConfig WxPayConfig = new WxPayConfig();
        WXPay wxPay = new WXPay(WxPayConfig);

        //根据微信支付api来设置
        Map<String, String> data = new HashMap<>();
        data.put("appid", WxPayConfig.getAppID());           //商户id
        data.put("mch_id", WxPayConfig.getMchID());         //商户号
        data.put("sub_appid",WxPayConfig.getAppID());     //小程序的APPID

        data.put("trade_type", "APP");                         //微信小程序支付
//        data.put("notify_url", notifyUrl);                     //回调地址
//        data.put("spbill_create_ip", "127.0.0.1");             //终端ip
//        data.put("total_fee", wxpayEntity.getTotalFee());       //订单总金额
//        data.put("fee_type", "CNY");                           //默认人民币
        data.put("transaction_id",wxpayEntity.getOutTradeNo()); //微信订单号
        data.put("out_trade_no", wxpayEntity.getOutTradeNo());   //商户订单号
        data.put("body", wxpayEntity.getBody());
        data.put("nonce_str", "");   // 随机字符串小于32位
        String s = WXPayUtil.generateSignature(data, WxPayConfig.getKey());  //签名
        data.put("sign", s);
//        wxPay.unifiedOrder这个方法中调用微信统一下单接口
        Map<String, String> respData = wxPay.unifiedOrder(data);
        if (respData.get("return_code").equals("SUCCESS")) {

            //返回给APP端的参数，APP端再调起支付接口
            Map<String, String> repData = new HashMap<>();
            repData.put("appid", WxPayConfig.getAppID());
            repData.put("partnerid", WxPayConfig.getMchID());
            repData.put("prepayid", respData.get("prepay_id"));
            repData.put("package", "WXPay");//数据包
            repData.put("noncestr", respData.get("nonce_str"));//随机串
            repData.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));//时间戳
            String sign = WXPayUtil.generateSignature(repData, WxPayConfig.getKey()); //签名
            respData.put("sign", sign);
            respData.put("timestamp", repData.get("timestamp"));
            respData.put("package", "WXPay");
            return respData;
        }
        throw new Exception(respData.get("return_msg"));

    }
}